<?php

/**
 * 抖音登录，获取token
 */

namespace app\client\services;

use think\facade\Cache;
use think\facade\Validate;

class TiktokService extends \app\admin\services\BaseService
{
    protected static $dev=false;
    const AppID='tt18ce6e7387f2b0f001';
    const AppSecret='122c084087e83510e2d2b6146b0544660481778f';

    /**
     * 通过baseurl组成requestUrl
     * @param $url 路由页面
     * @return string
     */
    protected static function getUrl($url){

        if(self::$dev){
            return 'https://open-sandbox.douyin.com'.$url;
        }else{
            return 'https://developer.toutiao.com'.$url;
        }
    }

    /**
     * 从缓存中获取AccessToken，如果过期则从平台刷新
     * @return mixed|void
     */
    protected static function getAccessToken(){
        $token=Cache::get('TiktokToken');
        if($token){
            return $token;
        }else{
            $res=self::refreshAccessToken();
            Cache::set($res->data->access_token, $res->data->expires_in);
            return $res->data->access_token;
        }
    }

    /**
     * 刷新抖音小程序AccessToken
     * @return mixed
     */
    protected static function refreshAccessToken(){
        $data=[
            'appid'=>self::AppID,
            'secret'=>self::AppSecret,
            'grant_type'=>'client_credential'
        ];
        return self::getDataByPostRequest('/api/apps/v2/token',$data);
    }

    /**
     * 登录操作
     * @param $p
     * @return void
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public static function login($p){
        $rule=[
            'code'=>'require',
        ];
        $validate=Validate::rule($rule);
        if(!$validate->check($p)){
            api_return(500,$validate->getError());
        }
        if($_SERVER['HTTP_HOST']=='www.yjm.com')
        {
            $res=new \stdClass();
            $res->session_key='123';
            $res->openid='_000XoFxUXjTNgtLpoBKwt0ghRN5sVrVmCn3';
            $res->unionid='0658f88a-aacf-4c72-824f-cafd690b415c';
            $res->dopenid='123';
        }else{
            $data=[
                'appid'=>self::AppID,
                'secret'=>self::AppSecret,
                'code'=>$p['code'],
            ];
            $res=self::getDataByPostRequest('/api/apps/v2/jscode2session',$data);
        }
        api_return(200,'',CustomerService::login($res->openid,'dy',($p['avatar'])??'',($p['username'])??'用户未授权',$res->unionid,($p['sharecode'])??''));
    }

    /**
     * 通过post请求获取抖音接口数据
     * @param $url 请求地址
     * @param $data 请求数据
     * @return mixed|void
     */
    protected static function getDataByPostRequest($url,$data){
        $url=self::getUrl($url);
        $header=[
            "content-type: application/json"
        ];
        $res=json_decode(post($url,json_encode($data),$header));
        if($res->err_no)
            api_return(500,$res->err_tips,$res);
        else{
            return $res->data;
        }
    }
}
